<template>
  <div class="c-bg-sgray c-pb40 container">
    <div class="c-pf c-pt0 c-bg-white c-flex-row c-aligni-center c-pl24 c-pv16 c-bgTittle c-pz10 c-w100" v-if="isRewoker==1">
      <div class="c-fs20 c-fc-FF2F0B">客观题不支持重新提交</div>
    </div>
    <div class="c-pb100" v-if="assign" :class="isRewoker==1?'c-pt60':''">
      <div class="c-ph24 c-pt20 c-bg-white">
        <div class="c-wb-ba">
          <div class="c-ws-n c-mt4 c-inlineblack fl c-fc-white c-fs18 c-ph4 c-pv2 c-br8 c-mr6 c-textAlign-c theme-bg">
            {{assign.isSubmit?'已提交':'未提交'}}
          </div>
          <div class="c-fs28 c-fc-xblack c-fw600">{{ assign.name }}</div>
        </div>
        <div class="c-fs22 c-fc-gray c-pt10 c-pb20">发布时间 {{assign.createdAt}} </div>
      </div>
      <div class="c-ph24">
        <div v-for="(item,index) in relates" :key="index">
          <div class="c-ph24 c-bg-white c-br20 c-mt22 c-p c-pt44 c-pb24">
            <div class="c-fs18 c-ph16 c-pv4 c-br-tl20 c-br-br20 c-pa c-p-t0 c-p-l0 theme-bg c-fc-white">{{item.type == 1
              ? "单选题"
              : item.type == 2
                ? "多选题"
                : item.type == 3
                  ? "简答题"
                  : item.type == 4
                    ? "判断题"
                    : item.type == 5
                      ? "填空题"
                      : item.type == 9?'阅读理解': ""}}</div>
            <problem :problemDate="item" :bigNumber="index"></problem>
            <div v-if="item.type==1||item.type==2||item.type==4">
              <single-choice :userAnswer="contents?contents[index]&&contents[index].answer:''" :isRewoker='isRewoker' :mId="item.mId" :questionInfo="item.questionDetail" :number="index" @pushAnswer="pushAnswer"></single-choice>
            </div>
            <div v-if="item.type==5">
              <fill-blanks :mId="item.mId" :userAnswer="contents&&contents[index]?contents[index].answer:''" :isRewoker='isRewoker' :questionInfo="item.questionDetail" :number="index" @pushAnswer="pushAnswer"></fill-blanks>
            </div>
            <div v-if="item.type==3">
              <esay-question :mId="item.mId" :answerText="contents&&contents[index]?contents[index].answer:''" :uploadImgList="contents&&contents[index]?contents[index].imgArr:[]"
                :uploadAudioList="contents&&contents[index]?contents[index].audioArr:[]" :uploadVideoList="contents&&contents[index]?contents[index].videoArr:[]" :questionInfo="item.questionDetail" :number="index" @pushAnswer="pushAnswer"></esay-question>
            </div>
          </div>
        </div>
        <loading-status-tem :dataStatus="dataStatus" noDataText="我也是有底线的"></loading-status-tem>
      </div>
    </div>
    <div class="c-pf c-p-l0 c-p-r0 c-p-b0 c-w100 c-hh88 c-ph24 c-flex-row c-flex-center c-bg-white">
      <div class="c-flex-grow1 c-fs24 c-hh64 c-br32 c-flex-row c-flex-center c-fc-white theme-bg c-fc-white" @click="submitSure">提交</div>
    </div>
  </div>
</template>

<script>
import { utilJs } from "@/utils/common.js";
import singleChoice from "@/components/templates/schoolAssignment/singleChoice.vue";
import fillBlanks from "@/components/templates/schoolAssignment/fillBlanks.vue";
import esayQuestion from "@/components/templates/schoolAssignment/essayQuestion.vue";
import problem from "@/components/templates/schoolAssignment/problem.vue";
let LIMIT = 10
let page = 1
let isLoading = null
export default {
  name: "SchoolAnswer",
  components: {
    singleChoice,
    fillBlanks,
    esayQuestion,
    problem
  },
  props: [],
  data() {
    return {
      showDesc: false, //显示课程
      uploadProgress: '0',
      ttId: "", //营期ID
      tpId: "", //环节ID
      tlId: "", //课时ID
      isWeiXin: true,
      assign:{},
      thwId:0,
      nobtn:false,
      homeworkType:1,
      isRewoker:0,
      relates:[],
      contents:[],
      newDate:[],
      idArr:[],
      leftAnswerNum:0
    };
  },
  created() {
    utilJs.appShare(this);
  },
  computed: {

  },
  methods: {
    pushAnswer(mId, answer, type) {
        if (type == 3) {
          for (let item in this.contents) {
            if (this.contents[item].thwrId == mId) {
              this.contents[item].type = type
              this.contents[item].answer = answer.answer
              this.contents[item].imgArr = answer.imgArr
              this.contents[item].audioArr = answer.audioArr,
              this.contents[item].videoArr = answer.videoArr
            }
          }
        } else {
          for (let item in this.contents) {
            if (this.contents[item].thwrId == mId) {
              this.contents[item].type = type
              this.contents[item].answer = answer
            }
          }
        }
        console.log(this.contents, '数据')
    },
    checkAnswer() {
      let removeFlag = true
      let contentsDate = this.contents
      let contentNew = []
      console.log(contentsDate, 'jianyan')
      for (let item in contentsDate) {
        if (contentsDate[item] && (contentsDate[item].type == 1 || contentsDate[item].type == 2 || contentsDate[item].type == 4)) {
            if (contentsDate[item].answer != '') {
              contentNew.push(contentsDate[item])
            }
        } else if (contentsDate[item] && contentsDate[item].type == 5) {
          let answerDate = contentsDate[item].answer || []
          for (let i in answerDate) {
            if (answerDate[i].value && answerDate[i].value != '') {
              removeFlag = true
              break
            } else {
              removeFlag = false
            }
          }
          console.log(!removeFlag || answerDate.length == 0, 4444444444444444)
          if (!(!removeFlag || answerDate.length == 0)) {
            contentNew.push(contentsDate[item])
          }
        } else if (contentsDate[item] && contentsDate[item].type == 3) {
          if (!(contentsDate[item].answer == '' && contentsDate[item].imgArr.length == 0 && contentsDate[item].audioArr.length == 0 && contentsDate[item].videoArr.length == 0)) {
            contentNew.push(contentsDate[item])
          } else if (contentsDate[item].id) {
            let date = {
              id:contentsDate[item].id,
              thwrId:contentsDate[item].thwrId
            }
            this.idArr.push(date)
          }
        } else if (!(contentsDate[item] && (!contentsDate[item].answer || contentsDate[item].answer == ''))) {
          contentNew.push(contentsDate[item])
        }
      }
      return contentNew
    },
    submitSure() {
      let $this = this
      this.idArr = []
      this.newDate = this.checkAnswer()
      console.log($this.relates.length - $this.newDate.length + Number($this.leftAnswerNum) )
      if ($this.assign.relates.total == Number($this.relates.length - $this.newDate.length + Number($this.leftAnswerNum))) {
        this.$cjConfirm({
            title: '完成提示', //
            titleCenter: true, //标题是否居中type == 3 ? '确定交卷?' : '恭喜你完成练习！1'
            message:'当前作业未答题，请完成作业后提交！', //弹窗内容,
            messageCenter: true, //内容是否居中
            showMasker: true, //是否显示透明背景
            clickCloseModal: false, //是否点击透明背景关闭弹窗
            showCancelButton: true, //是否显示取消按钮
            cancelButtonText: '', //取消按钮文本
            confirmButtonText: '', //确认按钮文本
            onConfirm() {
            }, //确认事件回调
            onCancel() {
            }, //取消事件回调
        })
        return;
      }
      if ($this.relates.length - $this.newDate.length + Number($this.leftAnswerNum) > 0) {
          this.$cjConfirm({
            title: '完成提示', //
            titleCenter: true, //标题是否居中type == 3 ? '确定交卷?' : '恭喜你完成练习！1'
            message:'当前作业有' + $this.assign.relates.total + '题，还有' + Number($this.relates.length - $this.newDate.length + Number($this.leftAnswerNum)) + '题未答题，是否提交作业', //弹窗内容,
            messageCenter: true, //内容是否居中
            showMasker: true, //是否显示透明背景
            clickCloseModal: false, //是否点击透明背景关闭弹窗
            showCancelButton: true, //是否显示取消按钮
            cancelButtonText: '', //取消按钮文本
            confirmButtonText: '', //确认按钮文本
            onConfirm() {
              $this.clickSubmit()
            }, //确认事件回调
            onCancel() {
            }, //取消事件回调
          })
      } else {
        $this.clickSubmit()
      }
    },
  //确认提交
  clickSubmit() {
      if (isLoading) {
        return;
      }
      isLoading = true;
      let that = this;
      // thwId	作业id
      // id	重新编辑提交作业时候用，第一次提交为0
      // contents	回答的内容
      // contents[0][thwrId]	题库作业列表的mId
      // contents[0][answer]	提交的答案
      // contents[0][imgArr]	提交的图片
      // contents[0][audioArr]	提交的音频
      let data = {
        thwId: this.thwId,
        contents: this.newDate,
        idArr:this.idArr
      };
      let postUrl = global.apiurl + `k12/trainings/saveUserTrainingHomeworkAnswer?ttId=${this.ttId}`;
      utilJs.postMethod(
        postUrl,
        data,
        (res) => {
          isLoading = false;
          localStorage.setItem(`camp${this.tlId}`, 100);
          // if (this.ckFrom == global.ckFrom.camp) {
            // 记录播放进度
            let data = {
              ttId: this.ttId, //营期ID
              tpId: this.tpId, //环节ID
              tlId: this.tlId, //课时ID
              ratio: 100 //完成进度0-100
            };
            utilJs.postMethod(
              global.apiurl + "k12/trainings/progress",
              data,
              function (res) {}
            );
          // }
          this.$showCjToast({
            text: "提交成功",
            type: "success",
          }).then(() => {
            that.clickLookShortAnswerResult(that.thwId)
          });
        },
        (failRes) => {
          isLoading = false;
        }
      );
    },
    clickLookShortAnswerResult(thwId) {
      console.log(thwId, '4545454')
      let querys = {
        thwId:thwId,
        homeworkType:this.homeworkType,
        ttId:this.ttId,
        tpId:this.tpId,
        tlId:this.tlId,
      }
      this.$routerGo(this, "replace", {
        path: "/homePage/schoolAssignment/answerResult",
        query: querys
      });
    },
    clickDesc() {
      if (this.showDesc) {
        this.showDesc = false;
      } else {
        this.showDesc = true;
      }
    },
    //获取详情
    getAssignDetail() {
      if (isLoading) {
        return
      }
      isLoading = true
      // let $this = this
      let postUrl = global.apiurl + "k12/trainings/" + this.thwId + '/getHomeworkDetail?ttId=' + this.ttId + '&page=' + page + '&limit=' + LIMIT;
      utilJs.getMethod(postUrl,
        res => {
          if (JSON.stringify(res) === '[]') {
            this.$showCjToast({
                text:"作业没有权限",
                type: "warn",
              });
              this.$routerGo(this, "replace", {
                path: `/homePage/camp/campDetail?campId=${this.ttId}`
              });
              return
            }
            this.assign = res
            this.leftAnswerNum = res.leftAnswerNum
            if (page == 1) {
                this.relates = res.relates.data
                for (let i in this.relates) {
                  let userAnswer = []
                  if (!this.relates[i].userAnswer) {
                    let data = {
                      thwrId:res.relates.data[i].mId,
                      type:res.relates.data[i].type,
                      answer:'',
                      imgArr:[],
                      audioArr:[],
                      videoArr:[]
                    }
                    userAnswer = data
                  } else {
                    res.relates.data[i].userAnswer.type = res.relates.data[i].type
                    userAnswer = res.relates.data[i].userAnswer
                  }
                    this.contents = [...this.contents, ... [userAnswer]]
                  // }
                }
            } else {
              for (let i in res.relates.data) {
                let userAnswer = []
                console.log(res.relates.data[i].userAnswer, 2323232323)
                if (!res.relates.data[i].userAnswer) {
                    let data = {
                      thwrId:res.relates.data[i].mId,
                      type:res.relates.data[i].type,
                      answer:'',
                      imgArr:[],
                      audioArr:[],
                      videoArr:[]
                    }
                    userAnswer = data
                  } else {
                    let setAnswer = res.relates.data[i].userAnswer
                    console.log(setAnswer, res.relates.data[i])
                    setAnswer.type = res.relates.data[i].type
                    userAnswer = setAnswer
                  }
                  console.log(this.relates.length)
                  this.contents = [...this.contents, ... [userAnswer]]
              }
              this.relates = [...this.relates, ... res.relates.data];
            }
            if (res.relates.data && (res.relates.data.length < LIMIT)) {
              this.dataStatus = page == 1 && res.relates.data.length == 0 ? 'NO_DATA' : 'NO_MORE_DATA';
            } else {
              this.dataStatus = 'HAS_MORE_DATA';
              page++;
            }
            isLoading = false
            console.log(this.contents, '获取做过数据')
            let that = this
            this.wechatShare()
            this.$nextTick(() => {
              //获取当前内容的行高，超过3行则显示更多
              let queryTextContent = document.querySelectorAll("#simpleText");
              console.log(queryTextContent)
              if (!queryTextContent) {
                return;
              }
              if (that.$refs.simpleText && that.$refs.simpleText.offsetHeight <= 89) {
                that.nobtn = false
              } else {
                that.nobtn = true
              }
            })
          }
      );
    },

    initData() {
      this.ttId = this.$route.query.ttId || "";
      this.tpId = this.$route.query.tpId || "";
      this.tlId = this.$route.query.tlId || "";
      this.thwId = this.$route.query.thwId || 0;
      this.contents = []
      page = 1
      this.leftAnswerNum = 0
      isLoading = null
      this.assign = {}
      this.relates = {}
      this.newDate = []
      this.homeworkType = this.$route.query.homeworkType || 1;
      this.isRewoker = this.$route.query.isRewoker || 0;
    },

    //分享
    wechatShare: function () {
      let title = this.assign.title || window.localStorage.getItem("companyName");
      let shareImg = this.assign.shareImg || window.localStorage.getItem("shareLogo");
      let shareDesc = this.assign.shareDesc || window.localStorage.getItem("shareDesc");
      let shareUrl = `${window.location.href.split("#")[0]}#/homePage/schoolAssignment/assignDetail?homeworkType=${this.homeworkType}&thwId=${this.thwId}&tlId=${this.tlId}&ttId=${this.ttId}&tpId=${this.tpId}&refereeId=${localStorage.getItem("userId")}`
      let shareIndexData = {
        shareUrl,
        title,
        shareImg,
        shareDesc,
      };
      utilJs.wechatConfig(
        shareIndexData.shareUrl,
        shareIndexData.title,
        shareIndexData.shareImg,
        shareIndexData.shareDesc,
        function () {},
        true
      );
    },
    //手机端分享
    appShare: function () {
      let title = this.assign.title || window.localStorage.getItem("companyName");
      let shareImg = this.assign.shareImg || window.localStorage.getItem("shareLogo");
      let shareDesc = this.assign.shareDesc || window.localStorage.getItem("shareDesc");
      let shareUrl = `${window.location.href.split("#")[0]}#/homePage/schoolAssignment/assignDetail?homeworkType=${this.homeworkType}&thwId=${this.thwId}&tlId=${this.tlId}&ttId=${this.ttId}&tpId=${this.tpId}&refereeId=${localStorage.getItem("userId")}`
      let shareIndexData = {
        shareUrl,
        title,
        shareImg,
        shareDesc,
      };
      utilJs.appShareTrue(
        shareIndexData.title,
        shareIndexData.shareImg,
        shareIndexData.shareUrl,
        shareIndexData.shareDesc
      );
    },
    windowScrollFunction() {
      utilJs.handleLoading(() => {
        if (this.dataStatus == 'HAS_MORE_DATA' && this.relates.length > 0) {
          this.getAssignDetail();
        }
      });
    },
  },
  activated() {
    this.initData();
    if (this.isRewoker == 1) {
      setDocumentTitle("修改作业")
    } else {
      setDocumentTitle("写作业")
    } // eslint-disable-line
    this.isWeiXin = utilJs.isWeiXin() && utilJs.isMobileUserAgent();
    window.addEventListener('scroll', this.windowScrollFunction);
    this.getAssignDetail()
  },
  deactivated() {

  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->

<style scoped>
.submit-bg {
  color: #fff;
  font-size: .55rem;
  border-radius: .8rem;
  text-align: center;
  height: 1.2rem;
  line-height: 1.2rem;
  padding: 0 1rem;
  /* background-image: linear-gradient(90deg, #FE9901 0%, #FEB74C 100%); */
}
.input-reset {
  border: 1px solid #e5e5e5!important;
}
.modal {
  z-index: 40003!important;
}
.modal-textarea {
  padding: 0.75rem 0 0.5rem 0rem;
  width: 100%;
  height: 4.9rem;
  display: flex;
  flex-direction: column;
  background-color: #F6F7F9;
  /* border-radius: .25rem; */
  padding-left: .5rem;
  padding-right: .5rem;
}

.modal-textarea textarea {
  font-size: 0.6rem;
  outline: none;
  border: none;
  width: 100%;
  height: 100%;
  background: none;
  -webkit-appearance: none;
  resize: none;
}

.modal-textarea textarea:focus {
  outline: none;
}
.del-img {
  position: absolute;
  top: 0rem;
  right: 0rem;
  /* cursor: pointer;
  background: rgba(0, 0, 0, 0.3); */
}
.del-icon  {
  position: absolute;
  top: -0.3rem;
  right: -0.3rem;
  width: .6rem;
  height: .6rem;
  border-radius: 50%;
  background: #FF4040;
  color: #fff;
  display: flex;
  justify-content: center;
  align-items: center;
}
.del-icon .iconfont{
  transform: scale(0.3);
  font-size: .8rem;
  display: block;
  font-weight: bold;
}

.box-bl-r8 {
  border-bottom-left-radius: 0.2rem;
  border-bottom-right-radius: 0.2rem;
}
.vux-popup-dialog {
  background-color: #fff;
  border-radius: 10px 10px 0 0;
}
.box {
  box-sizing: border-box;
  position: relative;
}
.wifi-symbol {
  width: 1rem;
  height: 1rem;
  overflow: hidden;
  position: relative;
  transform: rotate(135deg);
  -webkit-transform-origin: center;
  transform-origin: center;
  -webkit-transform: translate3d(135deg,0,0);
  -webkit-backface-visibility: hidden;
}
.wifi-circle {
  /* border: 0.1rem solid #999999; */
  border-radius: 50%;
  overflow: hidden;
  -webkit-backface-visibility: hidden;
  position: absolute;
  -webkit-transform: translate3d(0,0,0);
}

.first {
  width: 0.1rem;
  height: 0.1rem;
  background: #cccccc;
  top: 0.9rem;
  left: 0.9rem;
}
.second {
  width: 0.5rem;
  height: 0.5rem;
  top: 0.7rem;
  left: 0.7rem;
}
.seconAnimation{
  animation: fadeInOut 1s infinite 0.2s;
}
.third {
  width: 0.8rem;
  height: 0.8rem;
  top: 0.5rem;
  left: 0.5rem;
}
.thirdAnimation{
  animation: fadeInOut 1s infinite 0.4s;
}
@keyframes fadeInOut {
    0% {
        opacity: 0; /*初始状态 透明度为0*/
    }
    100% {
        opacity: 1; /*结尾状态 透明度为1*/
    }
}
.c-bgTittle{
  background-image: linear-gradient(270deg, #FEF2EB 0%, #FCE9F6 100%);
}
</style>
